package com.beiye.drivertransport.SubActivity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.frame.http.HttpUtils;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.utils.CustomProgressDialog;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.view.LinePathView;
import com.githang.statusbar.StatusBarCompat;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//驾驶员签字
public class SignActivity extends AppCompatActivity implements View.OnClickListener {
    //    @Bind(R.id.img_back1)
//    ImageView back;
//    @Bind(R.id.tv_clear)
//    TextView clear;
//    @Bind(R.id.tv_sure)
//    TextView sure;
//    @Bind(R.id.signatureview)
//    SignatureView signatureview;
    private Integer sn;
    final File fileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "Signname");
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private CustomProgressDialog dialog;
    private LinePathView signatureview;
    private TextView img_sign;
    private ImageView img_sign2;
    private int signMark;


    private static final String TAG = "SignActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);

        initData();
        ImageView back = (ImageView) findViewById(R.id.img_back1);
        //签名
        img_sign = (TextView) findViewById(R.id.img_sign1);
        TextView clear = (TextView) findViewById(R.id.tv_clear);
        TextView sure = (TextView) findViewById(R.id.tv_sure);
        signatureview = (LinePathView) findViewById(R.id.signatureview);

        back.setOnClickListener(this);
        clear.setOnClickListener(this);
        sure.setOnClickListener(this);
        img_sign.setOnClickListener(this);

    }
//    @OnClick({R.id.img_back1, R.id.tv_clear,R.id.tv_sure})


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_back1) {
            finish();
        } else if (id == R.id.tv_clear) {//重新签名
            img_sign2.setVisibility(View.GONE);
            img_sign.setVisibility(View.GONE);
            signatureview.clear();
        } else if (id == R.id.img_sign1) {//签名
            img_sign.setVisibility(View.GONE);
        } else if (id == R.id.tv_sure) {//保存签名

            try {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(SignActivity.this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showShortToast(SignActivity.this, "请到手机设置界面里找驾运宝允许开启读写手机存储,否则不能点确定");

                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            save(fileDir);
        }
    }


    public void initData() {
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        verifyStoragePermissions(this);
        Bundle bundle = getIntent().getExtras();
        sn = bundle.getInt("sn");
        String signPicUrl = bundle.getString("signPicUrl");
        signMark = bundle.getInt("signMark");
        img_sign2 = (ImageView) findViewById(R.id.img_sign2);
        if (signPicUrl.equals("")) {
            img_sign2.setVisibility(View.GONE);
        } else {
            img_sign2.setVisibility(View.VISIBLE);
            Picasso.with(SignActivity.this).load(Uri.parse(signPicUrl)).placeholder(R.mipmap.no_data1).into(img_sign2);//加载图片

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences sp = getSharedPreferences("SignActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
    }

    /**
     * 保存图片
     */
    private void save(File fileDir) {
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        //SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(new Date()) + ".png";
        LogUtils.e(TAG, "save: " + fileName);
        File savefile = new File(fileDir, fileName);

        String filePath = getFilePath(fileDir);
        if (signatureview.getTouched()) {//是否签名

            try {
                signatureview.save(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            uploadImg(savefile);//上传服务器封装方法

            //  Toast.makeText(SignActivity.this,"上传成功",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(SignActivity.this, "签名不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    private void uploadImg(File mediaFile) {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userName = data.getUserName();
        SharedPreferences sp = getSharedPreferences("SignActivity",
                Context.MODE_PRIVATE);
        int num = sp.getInt("num", 1);
        dialog = CustomProgressDialog.show(SignActivity.this, "保存中...", true, null);

        if (signMark == 1) {
            // mImgUrls为存放图片的url集合
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            if (mediaFile != null) {
                builder.addFormDataPart("signImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
                builder.addFormDataPart("sn", sn.toString());
                builder.addFormDataPart("userName", userName);
                builder.addFormDataPart("tSignMark", signMark + "");
            }
            MultipartBody requestBody = builder.build();
            //showLoadingDialog("正在加载");
            dialog = CustomProgressDialog.show(SignActivity.this, "保存中...", true, null);
            //构建请求
            Request request = new Request.Builder()
                    .url(AppInterfaceConfig.BASE_URL + "app/course/uploadSignFromApp")//地址
                    .post(requestBody)//添加请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtils.e(TAG, e.getLocalizedMessage() + "抛出异常");
                    dialog.dismiss();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    LogUtils.e(TAG, signMark + "" + str);
                    dialog.dismiss();
                    UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                    boolean result = upPhotoBean.isResult();
                    String msg = upPhotoBean.getMsg();
                    if (result) {
                        finish();
                    } else {
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(SignActivity.this);
                        builder1.setMessage(msg);
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });
                        builder1.create().show();
                    }
                }
            });
        } else if (signMark == 2 && num < 3) {
            // mImgUrls为存放图片的url集合
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            if (mediaFile != null) {
                builder.addFormDataPart("signImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
                builder.addFormDataPart("sn", sn.toString());
                builder.addFormDataPart("userName", userName);
                builder.addFormDataPart("tSignMark", signMark + "");
            }
            MultipartBody requestBody = builder.build();
            //showLoadingDialog("正在加载");
            dialog = CustomProgressDialog.show(SignActivity.this, "保存中...", true, null);
            //构建请求
            Request request = new Request.Builder()
                    .url(AppInterfaceConfig.BASE_URL + "app/course/uploadSignFromApp")//地址
                    .post(requestBody)//添加请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtils.e(TAG, e.getLocalizedMessage());
                    dialog.dismiss();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    LogUtils.e("上传成功", str);
                    UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                    boolean result = upPhotoBean.isResult();
                    String msg = upPhotoBean.getMsg();
                    dialog.dismiss();
                    if (result) {
                        finish();
                    } else {
                        SharedPreferences sp = getSharedPreferences("SignActivity",
                                Context.MODE_PRIVATE);
                        int num = sp.getInt("num", 1);
                        int num1 = num + 1;
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putInt("num", num1);
                        edit.commit();

                        Looper.prepare();
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(SignActivity.this);
                        builder1.setMessage(msg);
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });
                        builder1.create().show();
                        Looper.loop();
                    }


                }
            });


        } else if (signMark == 2 && num >= 3) {
            // mImgUrls为存放图片的url集合
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            if (mediaFile != null) {
                builder.addFormDataPart("signImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
                builder.addFormDataPart("sn", sn.toString());
                builder.addFormDataPart("userName", userName);
                builder.addFormDataPart("tSignMark", 1 + "");
            }
            MultipartBody requestBody = builder.build();
            //showLoadingDialog("正在加载");
            dialog = CustomProgressDialog.show(SignActivity.this, "保存中...", true, null);
            //构建请求
            Request request = new Request.Builder()
                    .url(AppInterfaceConfig.BASE_URL + "app/course/uploadSignFromApp")//地址
                    .post(requestBody)//添加请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtils.e("上传失败", e.getLocalizedMessage());
                    dialog.dismiss();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    LogUtils.e("上传成功", str);
                    UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                    boolean result = upPhotoBean.isResult();
                    String msg = upPhotoBean.getMsg();
                    dialog.dismiss();
                    if (result) {
                        finish();
                    } else {
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(SignActivity.this);
                        builder1.setMessage(msg);
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });
                        builder1.create().show();
                    }


                }
            });
        }

    }

    /**
     * 得到图片的路径 以及图片的名字
     */
    private String getFilePath(File fileDir) {
        //SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(new Date()) + ".png";
        LogUtils.e(TAG, "---" + fileName);
        File file = new File(fileDir, fileName);
        return file.getAbsolutePath();
    }

    public void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
